﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Schwazzle.Core.Model;
using Schwazzle.Core.Services;

namespace Schwazzle.WebParts.Schwazzle_Feed
{
    [ToolboxItemAttribute(false)]
    public partial class Schwazzle_Feed : WebPart
    {
        string templateListUrl = "http://vaiopony/sites/Schwazzle/Lists/Templates/AllItems.aspx";
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder javascriptText = new StringBuilder();
            
//   "<script language=javascript>" +
//   "function AlertHello() { alert('Hello ASP.NET'); }</script>");
            javascriptText.Append("<script type=\"text/javascript\">");
            javascriptText.Append("var feedEntries = [");
            IFeedService feedService = new RavenFeedService();
            IQueryable<FeedEntry> entries = feedService.GetUsersFeedEntry(this.Context.User.Identity.Name);
            string entriesText = string.Empty;
            foreach (FeedEntry entry in entries)
            {
                string json =  entry.GetJSON();
                entriesText += json + ",";
            }
            if (entriesText.Length > 0)
            { entriesText = entriesText.Substring(0, entriesText.Length - 1); }
            javascriptText.Append(entriesText);
            javascriptText.Append("];");
            using (SPSite templateSite = new SPSite(templateListUrl))
            {
                SPList templateList = templateSite.OpenWeb().GetListFromUrl(templateListUrl);
                javascriptText.Append("$.templates({");
                string templateText = string.Empty;
                foreach(SPListItem item in templateList.Items)
                {
                    templateText += item["Title"] + ": \"" + item["Template"] + "\",";
                }
                if (templateText.Length > 0)
                { templateText = templateText.Substring(0, templateText.Length - 1); }
                javascriptText.Append("});");
            }
            javascriptText.Append(" $(document).ready(function() {");
            javascriptText.Append("var html = $.render.titleTemplate( feedEntries );");
            javascriptText.Append("$( \"#feedList\" ).html( html );");
            javascriptText.Append("});");
            javascriptText.Append("</script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "TemplateFunctions", javascriptText.ToString());
            Repeater1.DataSource = entries;
            Repeater1.DataBind();
            listItems.DataSource = entries;
            listItems.DataBind();
        }
    }
}
